package co.com.smart.eagle.client.view.impl.components;

import com.google.gwt.cell.client.ButtonCell;
import com.google.gwt.core.client.GWT;
import com.google.gwt.safehtml.client.SafeHtmlTemplates;
import com.google.gwt.safehtml.shared.SafeHtml;
import com.google.gwt.safehtml.shared.SafeHtmlBuilder;
import com.google.gwt.safehtml.shared.SafeUri;
import com.google.gwt.safehtml.shared.UriUtils;

public class SmartImageCell extends ButtonCell {
	
	private String tooltipText;

    /**
     * The HTML templates used to render the cell.
     */
    interface Templates extends SafeHtmlTemplates {
      /**
       * The template for this Cell, which includes styles and a value.
       * 
       * @param styles the styles to include in the style attribute of the div
       * @param value the safe value. Since the value type is {@link SafeHtml},
       *          it will not be escaped before including it in the template.
       *          Alternatively, you could make the value type String, in which
       *          case the value would be escaped.
       * @return a {@link SafeHtml} instance
       */
      @Template("<img src=\"{0}\" title=\"{1}\" class=\"{2}\"></img>")
      SafeHtml cell(SafeUri value, String tootipText, String styleName);
      
      @Template("")
      SafeHtml cellHidden();
    }

    /**
     * Create a singleton instance of the templates used to render the cell.
     */
    private static Templates templates = GWT.create(Templates.class);

    public SmartImageCell() {

    }
    
    public SmartImageCell(String tooltipText) {
    	this.tooltipText = tooltipText;
    }


    @Override
    public void render(Context context, String value, SafeHtmlBuilder sb) {
      /*
       * Always do a null check on the value. Cell widgets can pass null to
       * cells if the underlying data contains a null, or if the data arrives
       * out of order.
       */
      if (value == null || value.equals("") ) {
        return;
      }

      String[] args = value.split(",");
      
      // If the value comes from the user, we escape it to avoid XSS attacks.
      SafeUri safeValue = UriUtils.fromSafeConstant(args[0]);
      
      
      boolean enabled = Boolean.valueOf(args[1]);     
      if(args.length > 2){
    	  this.tooltipText = args[2];
      }
      
      if(!enabled) 
      {
    	  this.tooltipText = "";
      }
      
      if(enabled){
    	  SafeHtml rendered = templates.cell(safeValue, (this.tooltipText != null ? this.tooltipText : ""), "clickImagen"); 
    	  sb.append(rendered);
      }
      else{    	  
    	  sb.append(templates.cellHidden());
      }
      
      
    }
}
